package com.example.component.b_fragment.container_change_qualifier

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.component.b_fragment.BFirstFragment
import com.example.component.b_fragment.BSecondFragment
import com.example.component.databinding.ActivityBABinding

class BAActivity : AppCompatActivity(), BFirstFragment.OnFragmentInteractionListener {
    private lateinit var binding: ActivityBABinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityBABinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initFragmentContainer()

        binding.changeFragmentBtn?.setOnClickListener {
            /**
             * 动态更换 Fragment
             */
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            fragmentTransaction.run {
                replace(binding.leftFragment.id, BSecondFragment.Companion.newInstance())
                // 将 BSecondFragment 添加到回退栈，
                // 添加到回退栈后，点击返回键，会返回到上一个页面
                addToBackStack(null)
                commit()
            }
        }
    }

    /**
     * 初始化 FragmentContainerView
     */
    private fun initFragmentContainer() {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.run {
            add(binding.leftFragment.id, BFirstFragment::class.java, null)
            commit()
        }
    }

    override fun onFragmentInteraction(data: String) {
        // 处理来自 Fragment 的数据
    }
}